import flask
from flask import Blueprint
import db

page_briefing = Blueprint('page_briefing', __name__)


@page_briefing.route('/item_<gid>')
def itemInfo(gid):
    """
    page show info of goods item and update info
    :param gid: ID of the item
    :return: null
    """
    info, comment = db.get_item_info(int(gid))
    user_id = flask.request.cookies.get('userid')
    if user_id is not None:
        basic, up, deals, fav = db.get_user_info(userid=user_id)
        aut = basic['aut']
        name = basic['name']
    else:
        aut = None
        name = None
    return flask.render_template('static/templates/briefing.html', info=info, comment=comment, aut=aut, name=name)


@page_briefing.route('/buy', methods=['POST'])
def buy():
    """
    make a purchase, handle a POST request
    :return: operation status
    """
    deal = flask.request.form
    db.new_deal(deal['buyer_id'], deal['seller_id'], deal['gid'])
    return 'good'


@page_briefing.route('/add_comment', methods=['POST'])
def add_comment():
    """
    add a comment to db, the request should contain all the
    info that needed
    :return: a confirming message 'good'
    """
    gid = flask.request.form.get('gid')
    time = flask.request.form.get('time')
    commenter = flask.request.form.get('commenter')
    text = flask.request.form.get('text')
    reply_to = flask.request.form.get('replyTo')
    db.insert_comment(gid, time, commenter, text, reply_to)
    return 'good'


@page_briefing.route('/like', methods=['POST'])
def like():
    """
    add an item to user's favorites
    :return: operation status
    """
    info = flask.request.form
    rt = db.insert_favorites(info['uid'], info['gid'])
    return rt


@page_briefing.route('/remove_cmt', methods=['POST'])
def rm_comment():
    """
    remove a comment, level 3 and 2 users have authority to remove comment from anyone,
    level 1 users can only remove comments posted by themselves
    :return: operation status
    """
    info = flask.request.form
    cur_user = flask.request.cookies.get('userid')
    basic, up, deals, fav = db.get_user_info(userid=cur_user)
    if info['commenter'] == basic['name']:  # 删除自己的评论
        db.remove_comment(info.get('cid'))
        return '您发布评论已删除'
    if basic['aut'] == 3 or basic['aut'] == 2:  # 有删除评论的权限
        db.remove_comment(info.get('cid'))
        return '您已删除其他用户的评论，请不要做权限狗'
    return '您无权删除别人的评论'
